<?php

function get_unique_str( $len = 8 ){
	$s = 'abcdefghijkmnopqrstuvwxyz23456789';
	$str = '';
	$max = strlen($s) - 1;
	for($i = 1;$i <= $len; $i++){
        $str .= $s{rand(0,$max)};
    }
	return $str;
}

function get_unique_url( $len=8 ){
	
	$url = get_unique_str( $len );
	$note = query_note_by_url( $url);
	
	if( empty($note)){
		return $url;
	}else{
		return get_unique_url( $len );
	}
}

function create_unique_note( $len=8 ){
	$user = create_user_for_cookie();
	$url = get_unique_url( $len );
	$note = array(
		'url'=>$url,
		'owner'=>$user['id'],
		'content'=>''
	);
	$note = save_note( $note );
	
	return $note;
}

function create_url_note( $url ){
	$user = create_user_for_cookie();
	$note = array(
		'url'=>$url,
		'owner'=>$user['id'],
		'content'=>''
	);
	$note = save_note( $note );
	return $note;
}

function get_note_by_url($url,$view=true){
	global $note;
	$note = query_note_by_url($url);
	if( $view && !empty($note) ){
		update_note_views( $note['id'] );
	}
}

function query_note_by_url($url){
	global $db;
	$query = $db->query("select * from note where url = '".$url."'");
	$note = $db->fetch_array($query);	
	return $note;
}

function update_note_views($note_id,$times=1){
	global $db;
	$db->query('update note set views=views+'.$times.' where id='.$note_id);
}
/**
 * insert or update
 * @param $note Note array
 */
function save_note($note){
	
	if( isSet($note['id']) ){
		update_note($note);
		return $note;
	}
	
	$n = query_note_by_url($note['url']);
	
	
	if( empty($n) ){ 	//insert
		create_note($note);
		$note = query_note_by_url($note['url']);
		return $note;
	}else{
		return;
	}
}

function create_note($note){
	global $db;
	$db->query("insert into note (url,content,title,owner) values('".$note['url']."','".$note['content']."','".auto_title($note['content'])."',".$note['owner'].")");
}

function update_note($note){
	global $db;
	$db->query("update note set url='".$note['url']."',content='".$note['content']."',title='".auto_title($note['content'])."' where id=".$note['id']);
}

function query_user_by_name($username){
	global $db;
	$query = $db->query("select * from user where username = '".$username."'");
	$user = $db->fetch_array($query);	
	return $user;
}

function query_user_by_id( $id ){
	global $db;
	$query = $db->query("select * from user where id = ".$id);
	$user = $db->fetch_array($query);	
	return $user;
}

function get_unique_username( $len = 32){
	$username = get_unique_str( $len );
	$user = query_user_by_name( $username );
	
	if( empty($user)){
		return $username;
	}else{
		return get_unique_username( $len );
	}
}

function create_user_for_cookie(){

	if( isSet($_COOKIE['username']) ){
		$real_user = query_user_by_name(xnote_escape($_COOKIE['username']));
		if( $real_user['password'] ==  $_COOKIE['password'] ){
			return $real_user;
		}
	}

	$user['username'] = get_unique_username();
	$user['password'] = get_unique_str(32);
	$user['source'] = 'cookie';
	
	global $db;
	$db->query("insert into user(username,password,source) values('".$user['username']."','".$user['password']."','".$user['source']."')");
	
	setcookie("username", $user['username'] , time()+60*60*24*7);
	setcookie("password", $user['password'] , time()+60*60*24*7);
	
	return query_user_by_name($user['username']);
}

function user_can_edit( $url ){
	$note = query_note_by_url( $url );
	
	if( empty( $note )){
		return true;
	}
	
	$user = query_user_by_id ( $note['owner'] );
	if(
		isSet($_COOKIE["username"]) 
		&& $user['username'] == $_COOKIE["username"]
		&& isSet($_COOKIE['password'] )
		&& $user['password'] == $_COOKIE['password']){
		return true;
	}else{
		return false;
	}
}

function auto_title($content){
	$content = trim($content);
	$content = explode("\n",$content);
	$content = $content[0];
	return mysubstr($content,0,min(strlen($content),30));
}
function mysubstr($str, $start, $len) { 
    $tmpstr = ""; 
    $strlen = $start + $len; 
    for($i = 0; $i < $strlen; $i++) { 
        if(ord(substr($str, $i, 1)) > 0xa0) { 
            $tmpstr .= substr($str, $i, 2); 
            $i++; 
        } else 
            $tmpstr .= substr($str, $i, 1); 
    } 
    return $tmpstr; 
}

function xnote_escape($str){
	if (get_magic_quotes_gpc()) {
		return stripslashes($str);
	}else{
		return mysql_real_escape_string($str);
	}
}